package com.gongpingjialoan.activity.loans;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.api.Piont;
import com.gongpingjialoan.bean.AssessmentData;
import com.gongpingjialoan.bean.SellerValueBean;
import com.gongpingjialoan.data.UserManager;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.manage.PointRecordManage;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.utility.ArithUtil;
import com.gongpingjialoan.widget.LoadingDialog;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import static com.alibaba.sdk.android.feedback.impl.FeedbackAPI.mContext;

/**
 * 预估可贷款金额
 */
public class EstimatedLoanAmountActivity extends BaseActivity {
    private AssessmentData ad = AssessmentData.getInstance();
    private NetDataJson mSellValueNetDataJson;
    private LoadingDialog loadingDialog;
    private SellerValueBean mSellValueBean = new SellerValueBean();

    private TextView amountT,loan_amountT;
    private EditText nameEt;
    private TextView submitT;
    private Double eval_price,newGood;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_estimated_loan_amount);
        initView();
    }

    private void initView() {
        PointRecordManage.getInstance().addPoint(mySelf, Piont.MortgageResultView);
        setTitle("预估可贷金额");
        amountT = (TextView) findViewById(R.id.amount);
        loan_amountT = (TextView) findViewById(R.id.loan_amount);
        nameEt = (EditText) findViewById(R.id.name);
        submitT = (TextView) findViewById(R.id.submit);

        nameEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                isClick();
            }
        });
        submitT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PointRecordManage.getInstance().addPoint(mySelf, Piont.MortgageResultCommit);
                submit();
            }
        });

        loadingDialog = new LoadingDialog(mySelf);
        if (!loadingDialog.isShowing()) {
            loadingDialog.show();
        }
        initSellValue();
    }

    private void isClick(){
        submitT.setEnabled(false);
        submitT.setBackgroundResource(R.color.text_grey);

        String name = nameEt.getText().toString().trim();
        if (TextUtils.isEmpty(name)){
            showTips(1,"请输入您的姓名");
            return;
        }
        submitT.setEnabled(true);
        submitT.setBackgroundResource(R.color.blue_3fbbff);
    }

    private void submit() {


        NetDataJson netDataJson = new NetDataJson(new NetDataJson.OnStringListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
                Toast.makeText(mContext, errorMessage, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDataJsonUpdate(String json) {
                try {
                    JSONObject jo = new JSONObject(json);
                    if (jo == null) {
                        return;
                    }
                    if ("error".equals(jo.getString("status"))) {
                        Toast.makeText(mContext, jo.getString("msg"), Toast.LENGTH_SHORT).show();
                        return;
                    }
                    PointRecordManage.getInstance().addPoint(mySelf, Piont.MortgageResultSuccess);
                    showTips(1,"提交成功，金融专员将尽快与您联系，请耐心等待……");
                    setResult(Activity.RESULT_OK,getIntent());
                    finish();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, 1);
        UserManager mUserManager = new UserManager(mySelf);
        mUserManager = mUserManager.LoadUserInfo();
        JSONObject jo = getExtraData();

        netDataJson.setUrl(NetDataJson.LOAN_SERVER_DOMAIN + API.chedidai_orders);
        netDataJson.setUseOtherDomain(true);
        netDataJson.addParam("name",nameEt.getText().toString().trim());
        netDataJson.addParam("mobile",mUserManager.getPhone());
        netDataJson.addParam("city",ad.getCity());
        netDataJson.addParam("detail_model_slug",ad.getModelDetailSlug());
        netDataJson.addParam("extra_data",jo.toString());
        netDataJson.addParam("term",36);
        netDataJson.request("post");
    }

    private JSONObject getExtraData() {
        JSONObject jo = new JSONObject();
        try {
            jo.put("brand",ad.getBrandSlug());
            jo.put("brand_zh",ad.getBrandName());
            jo.put("model",ad.getModelSlug());
            jo.put("model_zh",ad.getModelName());
            jo.put("model_detail",ad.getModelDetailSlug());
            jo.put("model_detail_zh",ad.getModelName() + " "+ ad.getModelDetailName());
            jo.put("year",ad.getYear());
            jo.put("month",ad.getMonth());
            jo.put("mile",ad.getMile());
            jo.put("eval_price",ArithUtil.mul(newGood,10000d).intValue());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jo;
    }

    //估值
    private void initSellValue() {

        mSellValueNetDataJson = new NetDataJson(new NetDataJson.OnStringListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
                if (loadingDialog.isShowing()) {
                    loadingDialog.dismiss();
                }

                Toast.makeText(mySelf, errorMessage, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDataJsonUpdate(String json) {
                if (loadingDialog.isShowing()) {
                    loadingDialog.dismiss();
                }
                if (!GPJApplication.getInstance().isLogin() && getSharedPreferences("GetPhone", MODE_PRIVATE).getBoolean("isShowGetPhoneDialog", true)) {
//                    showGetPhoneDialog();
                }
                Gson gson = new Gson();
                mSellValueBean = gson.fromJson(json, SellerValueBean.class);
                if ("success".equals(mSellValueBean.getStatus())) {
                    Double good = mSellValueBean.getData().getEval_prices().getPrivateX().getGood();
                    newGood = ArithUtil.setScale(good,1);
                    amountT.setText(newGood + "");
                    java.text.DecimalFormat  df = new java.text.DecimalFormat("##,###,###");
                    eval_price = ArithUtil.mul(ArithUtil.setScale(ArithUtil.mul(newGood,0.9d),1),10000d); //计算单款金额 保留一位小数在计算
//                    eval_price = ArithUtil.mul(ArithUtil.mul(good,10000d),0.9d);
                    loan_amountT.setText(df.format(eval_price));
                } else {
                    Toast.makeText(mySelf, mSellValueBean.getMsg(), Toast.LENGTH_SHORT).show();
                }
            }
        }, 1);
        mSellValueNetDataJson.setUrl(API.sell_value);
        mSellValueNetDataJson.addParam("brand", ad.getBrandSlug());
        mSellValueNetDataJson.addParam("model", ad.getModelSlug());
        mSellValueNetDataJson.addParam("model_detail", ad.getModelDetailSlug());
        mSellValueNetDataJson.addParam("year", ad.getYear());
        mSellValueNetDataJson.addParam("month", ad.getMonth());
        mSellValueNetDataJson.addParam("city", ad.getCity());
        mSellValueNetDataJson.addParam("mile", ad.getMile());
        mSellValueNetDataJson.request("get");
        if (!loadingDialog.isShowing()) {
            loadingDialog.show();
        }
    }

    @Override
    protected void onDestroy() {
        PointRecordManage.getInstance().addPoint(mySelf, Piont.ReckonResultBack);
        if (mSellValueNetDataJson != null) {
            mSellValueNetDataJson.cancelTask();
        }
        super.onDestroy();
    }
}
